<template>
<highlightjs language="JavaScript" highlightAuto top :code="code" />
</template>
<script>
export default {
  setup () {
    const code = `
    const state = reactive({
      map: ref(null),
      mapBox: ref(null),
      popup: ref(null),
      overlay: null,
      shopPopup: false
    })

    const init = () => {
      // 创建图标特性
      const iconFeature = new Feature({
        geometry: new Point([0, 0]), // 图标位置
        name: '你点我了',
        population: 4000,
        rainfall: 500
      })

      const iconStyle = new style.Style({
        image: new style.Icon({
          anchor: [0.5, 46], // 根据图标的大小，对应上面 [0, 0] 的坐标
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          src: iconPng // 或者 src: require('../../assets/images/icon.png')
        })
      })

      // 把样式应用到图标上
      iconFeature.setStyle(iconStyle)

      // 创建矢量容器，将图标特性添加进容器中
      const vectorSource = new VectorSource({
        features: [iconFeature]
      })

      // 创建矢量图层
      const vectorLayer = new VectorLayer({
        source: vectorSource
      })

      // 底图源
      const rasterLayer = new Tile({
        source: new XYZ({
          url: 'https://api.maptiler.com/maps/topographique/256/{z}/{x}/{y}.png?key=B3EG5uYPUvFucEWVoCa3',
          crossOrigin: ''
        })
      })

      state.map = new Map({
        target: state.mapBox,
        layers: [rasterLayer, vectorLayer],
        view: new View({
          // 地图视图
          projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3857
          center: [0, 0],
          zoom: 1 // 地图缩放级别（打开页面时默认级别）
        })
      })

      mapClick()
    }

    const mapClick = () => {
      state.map.on('singleclick', evt => {
        // 创建弹窗并添加到Map
        state.overlay = new Overlay({
          element: state.popup,
          positioning: 'bottom-center',
          stopEvent: false,
          offset: [0, -50]
        })
        state.map.addOverlay(state.overlay)

        // 获取图层
        const feature = state.map.forEachFeatureAtPixel(evt.pixel, function (feature) {
          return feature
        })

        // 判断如果有图层时显示弹窗否则不显示
        if (feature) {
          state.shopPopup = true
          state.popup.innerHTML = feature.values_.name
          state.overlay.setPosition(evt.coordinate)
        } else {
          state.shopPopup = false
        }
      })
    }
    `
    return {
      code
    }
  }
}
</script>
